package org.leo.app;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.SetArgs;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Map;

public class SyncTest {

    static RedisClient redisClient;
    static StatefulRedisConnection<String, String> conn;

    /**
     * 初始化 RedisClient StatefulRedisConnection 的方法
     */
    public static void init() {
        // 创建 RedisURI 对象
        RedisURI redisUri = RedisURI.builder()
                .withHost("localhost")
                .withPassword(new char[]{'3', '1', '9', '6', '1', '1'})
                .withDatabase(0)
                .withPort(6379)
                .withTimeout(Duration.of(10, ChronoUnit.SECONDS))
                .build();
        // 创建 RedisClient
        redisClient = RedisClient.create(redisUri);
        // 获取 StatefulRedisConnection
        conn = redisClient.connect();
    }

    public static void closeResource() {
        // 关闭连接
        conn.close();
        // 关闭客户端
        redisClient.shutdown();
    }

    public static void main(String[] args) {
        init();
        // 创建 StatefulRedisConnection
        StatefulRedisConnection<String, String> connection = redisClient.connect();

        // 创建同步模式的 RedisCommands
        RedisCommands<String, String> redisCommands = connection.sync();

        // 设置超时时长
        SetArgs setArgs = SetArgs.Builder.nx().ex(2000);

        // 执行 ping
        System.out.println(redisCommands.ping());

        // 执行 set
        String result1 = redisCommands.set("name", "齐龙鑫", setArgs);
        System.out.println(result1);

        // 执行 hset
        Long result2 = redisCommands.hset("user", Map.of("name",  "qlx", "age", "20", "address", "上海"));
        System.out.println(result2);

        // 执行 get
        String result3 = redisCommands.get("name");
        System.out.println(result3);

        // 执行 hget
        System.out.println(redisCommands.hget("user", "address"));

        // 关闭资源
        closeResource();
    }
}